package templates;

public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5};
        System.out.println(binarySearch(nums,4));
    }

    private static int binarySearch(int[] nums, int key) {
        if (nums == null || nums.length < 1){
            return -1;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right){
            int center = (right + left)/2;
            if (nums[center] < key){
                left = center + 1;
            }else if (nums[center] > key){
                right = center - 1;
            }else {
                return center;
            }
        }
        return -1;
    }
}
